﻿using CommonTools;
using Newtonsoft.Json;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.cost
{
    public class GoodsOperatorBll : IPageBll<GoodsOperator>
    {
        public string Title => "运营负责人";

        public bool EnableEditOnList => true;

        public bool EnableCreateOnList => true;

        public bool RefreshOnOpen => true;
        public Action<int> TurnPage { set; get; }

        public GoodsOperator CopyItem(GoodsOperator item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.Id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public GoodsOperator CreateItem()
        {
            return new GoodsOperator() { isdel = false,  };
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<GoodsOperator>()
                .Where(a => a.Id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            //await DB.FSql.Insert(new CLogs()
            //{
            //    DocName = nameof(GoodsOperator),
            //    Computer = UserBll.CurrentUser.ComputerInfo,
            //    Zdr = UserBll.CurrentUser.Name,
            //    DocId = id.ToString(),
            //    DocAction = "删除",
            //})
            //    .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string dataPropertyName, object value, GoodsOperator data)
        {
            if (data.Id == 0)
            {
                //data.FTime = await DB.FSql.GetTimeAsync();
                //data.FUser = UserBll.CurrentUser.Name;
                data.isdel = false;

                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.Id = (int)nid;

            }

            var dbRes = await DB.FSql.Update<GoodsOperator>()
                .Where(a => a.Id == data.Id && a.isdel == false)
                .SetDto(new Dictionary<string, object> { [dataPropertyName] = value })
                .ExecuteAffrowsAsync();

            return new Result<int>(true, null, data.Id);
        }

        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
           {
                new DeclareColumn(nameof(GoodsOperator.Id),"Id"){ Visible= false},
                new DeclareColumn(nameof(GoodsOperator.platform_goods_id),"货品平台ID"){Width=170},
                new DeclareColumn(nameof(GoodsOperator.Operator),"运营负责人"){ Width=130 },
            };

        }

        public async Task<GoodsOperator> GetItem(int id)
        {
            var list = await DB.FSql.Select<GoodsOperator>()
                .Where(a => a.isdel == false && a.Id == id)
                .ToOneAsync();
            return list;
        }



        #region 查询参数

        private string _gid;
        private string _op;


        #endregion

        /// <summary> 查询ui </summary>
        public virtual ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .AddGuanTextBox("货品平台ID", c => _gid= c)
                .AddGuanTextBox("运行负责人", c => _op= c)
                .AddQueryButton("查询");
        }


        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<GoodsOperator>> QueryPage(DocFilterParameter queryPara)
        {
            var list = await DB.FSql.Select<GoodsOperator>()
                .Where(a => a.isdel == false)
                .WhereIf(!string.IsNullOrEmpty(_gid), a => a.platform_goods_id.Contains(_gid))
                .WhereIf(!string.IsNullOrEmpty(_op), a => a.Operator.Contains(_op))
                .Page(queryPara.PageNo, queryPara.PageSize)
                .OrderByDescending(a => a.Id)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<GoodsOperator>(true, null, list, c);
        }



        public async Task<Result> SaveItem(GoodsOperator item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }


            string err = string.Empty;
            if (string.IsNullOrEmpty(item.platform_goods_id))
            {
                err += "货品平台ID不能为空";
            }

            if (string.IsNullOrEmpty(item.Operator))
            {
                err += "运营负责人不能为空";
            }

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;

            if (item.Id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.Id = (int)id;
            }
            else
            {
                await DB.FSql.Update<GoodsOperator>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);

        }


        public async Task<Result> SaveItem(IEnumerable<GoodsOperator> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }


            //var time = await DB.FSql.GetTimeAsync();

            foreach (var item in items)
            {
                item.isdel = false;
            }

            await DB.FSql.Insert(items).ExecuteAffrowsAsync();
            //删除重复的
            var cmd = @"UPDATE  GoodsOperator SET isdel =1
FROM GoodsOperator INNER JOIN (
SELECT a.platform_goods_id, MIN(a.Id) mid 
FROM dbo.GoodsOperator AS a
where a.isdel =0 
GROUP BY a.platform_goods_id
HAVING COUNT(*)>1) AS b ON GoodsOperator.id= b.mid
where GoodsOperator.isdel=0";

            await DB.FSql.Ado.ExecuteNonQueryAsync(System.Data.CommandType.Text, cmd, null);

            return new Result(true);

        }


    }
}
